<?php

class MySQL
{
	function __construct()
	{
		$this->link = false;
	}
	
	function __destructor()
	{
		@mysql_close();
	}
	
	function connect($sql_host, $sql_user, $sql_pass, $db_name, $db_debug = "OFF")
	{
		$this->host = $sql_host;
		$this->user = $sql_user;
		$this->pass = $sql_pass;
		$this->db = $db_name;
		$this->debug = $db_debug;
		
		$this->link = @mysql_connect($this->host, $this->user, $this->pass);
		
		if(!$this->link)
			$this->error("Impossibile aprire una connessione al server MySQL: $this->host.");
		
		if(!@mysql_select_db($this->db, $this->link))
			$this->error("Impossibile aprire il database: $this->db.");
	}
	
	function close()
	{
		if(!@mysql_close())
			$this->error("Errore durante la chiusura della connessione al server MySQL.");
	}
	
	function escape($string)
	{
		if(get_magic_quotes_gpc())
			$string = stripslashes($string);
		
		if(phpversion() >= "4.3.0")
			$string = mysql_real_escape_string($string);
		else
			$string = mysql_escape_string($string);

		return $string;
	}
	
	function query($sql)
	{
		$this->query = @mysql_query($sql, $this->link);
		
		if(!$this->query)
			$this->error("Query MySQL fallita: $sql");
		
		$this->affected_rows = @mysql_affected_rows();
		$this->num_rows = @mysql_num_rows($this->query);
	}
	
	function get_affected_rows()
	{
		return $this->affected_rows;
	}
	
	function get_num_rows()
	{
		return $this->num_rows;
	}
	
	function fetch_array()
	{
		if(isset($this->query))
			$this->record = @mysql_fetch_assoc($this->query);
		else
			$this->error("Errore durante il fetching della query: $this->query.");
		
		if($this->record)
			$this->record = array_map("stripslashes", $this->record);
		
		return $this->record;
	}
	
	function free_result()
	{
		if(!@mysql_free_result($this->query))
			$this->error("Errore durante le operazioni di freed della query: $this->query.");
	}
	
	function error($msg)
	{
		if($this->link > 0)
		{
			$this->error = mysql_error($this->link);
			$this->errno = mysql_errno($this->link);
		}
		
		$this->error = mysql_error();
		$this->errno = mysql_errno();
		
		if($this->debug == "ON")
		{
			echo "<br><br><b>Errori Database MySQL</b><br><br>";
			echo "MySQL Error: " . $this->error . "<br>";
			echo "$msg<br>";
		}
	}
}
